package top.guxx.mall.consumer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import top.guxx.mall.dao.IProductDao;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * @Author：Guxx
 * @Description：延迟队列库存扣减
 * @Date：2025/2/23 6:26
 * @Filename：DelayedQueueConsumer
 */

@Service
@Slf4j
public class DelayedQueueConsumer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IProductDao productDao;

    private static final String DELAYED_QUEUE_KEY = "delayedQueue";

    /**
     * 定时任务，处理延迟队列中的任务
     */
    @Scheduled(fixedRate = 1000 * 60) // 每隔1分钟检查一次
    public void processDelayedTasks() {
        long currentTime = System.currentTimeMillis();
        Set<String> tasks = stringRedisTemplate.opsForZSet().rangeByScore(DELAYED_QUEUE_KEY, 0, currentTime);

        if (tasks != null && !tasks.isEmpty()) {
            for (String massage : tasks) {
                // 执行任务
                executeTask(massage);
                // 从队列中移除已执行的任务
                stringRedisTemplate.opsForZSet().remove(DELAYED_QUEUE_KEY, massage);
                log.info("Task " + massage + " is executed.");
            }
        }
    }

    /**
     * 模拟任务执行
     * @param massage 消息体
     */
    private void executeTask(String massage){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(massage, Map.class);
            String key = map.entrySet().iterator().next().getKey();
            productDao.inventoryDeduction(key, Integer.parseInt(map.get(key).toString()));
            log.info("Task " + massage + " is executing...");
        }catch (JsonProcessingException e){
            log.error("JSON序列化失败！",e);
        }
    }
}